package cn.wolfcode.education.web.controller;

import cn.wolfcode.education.anno.PermissionName;
import cn.wolfcode.education.domain.Employee;
import cn.wolfcode.education.domain.Payroll;
import cn.wolfcode.education.query.PayrollQuery;
import cn.wolfcode.education.service.IPayrollService;
import cn.wolfcode.education.util.JSONResult;
import cn.wolfcode.education.util.PageResult;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("payroll")
public class PayrollController {
    @Autowired
    private IPayrollService payrollService;

    @RequestMapping("")
    public String index() {
        return "payroll";
    }

    //工资列表
    @RequestMapping("list")
    @ResponseBody
    @RequiresPermissions("payroll:list")
    @PermissionName("工资列表")
    public PageResult list(PayrollQuery qo) {
        return payrollService.queryAll(qo);
    }

    //工资修改
    @PermissionName("工资修改")
    @RequiresPermissions("payroll:update")
    @RequestMapping("update")
    @ResponseBody
    public JSONResult update(Payroll payroll) {
        System.out.println(12345);
        JSONResult jsonResult = new JSONResult();
        try {
            payrollService.update(payroll);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("系统崩溃了,攻城狮正在努力攻城!");
        }
        return jsonResult;
    }

    @PermissionName("工资删除")
    @RequiresPermissions("payroll:delete")
    @RequestMapping("delete")
    @ResponseBody
    public JSONResult delete(Long id) {
        JSONResult jsonResult = new JSONResult();
        try {
            payrollService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("系统崩溃了,攻城狮正在努力攻城!");
        }
        return jsonResult;
    }

    @PermissionName("工资结算")
    @RequiresPermissions("payroll:adjust")
    @RequestMapping("adjust")
    @ResponseBody
    public JSONResult adjust(Long id) {
        JSONResult jsonResult = new JSONResult();
        try {
            Payroll payroll = payrollService.selectPrimaryByKey(id);
            int afterDays = payroll.getAfterDays();
            int beforeDays = payroll.getBeforeDays();
            int finalSalary = payroll.getBaseSalary().intValue() - 100 * (afterDays + beforeDays);
            payroll.setFinalSalary(new BigDecimal(finalSalary));
            payrollService.updatePayTime(id, new Date(), new BigDecimal(finalSalary));
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("系统崩溃了,攻城狮正在努力攻城!");
        }
        return jsonResult;
    }

    //表格导出
    @RequestMapping("export")
    @ResponseBody
    @PermissionName("员工导出")
    @RequiresPermissions("payroll:export")
    public void export(PayrollQuery qo, HttpServletResponse response) throws Exception {
        //1.查询出列表数据
        qo.setRows(1000);
        List payrolls = payrollService.queryForList(qo);
        response.setHeader("Content-Disposition", "attachment;filename=payroll.xls");
        OutputStream outputStream = response.getOutputStream();
        //创建一个 工作簿,目标是outputStream
        WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
        //2.处理标题
        //创建一个可以写sheet
        WritableSheet sheet = workbook.createSheet("payroll", 0);
        //创建一个单元格
        Label idLabel = new Label(0, 0, "员工编号");
        Label monthLabel = new Label(1, 0, "月份");
        Label realNameLabel = new Label(2, 0, "员工姓名");
        Label baseSalaryLabel = new Label(3, 0, "基本工资");
        Label workDaysLabel = new Label(4, 0, "工作天数");
        Label afterDaysLabel = new Label(5, 0, "迟到天数");
        Label beforeDaysLabel = new Label(6, 0, "早退天数");
        Label upDaysLabel = new Label(7, 0, "补签天数");
        Label finalSalaryLabel = new Label(8, 0, "最终工资");
        Label payTimeLabel = new Label(9, 0, "结算时间");
        //添加标题
        sheet.addCell(idLabel);
        sheet.addCell(monthLabel);
        sheet.addCell(realNameLabel);
        sheet.addCell(baseSalaryLabel);
        sheet.addCell(workDaysLabel);
        sheet.addCell(afterDaysLabel);
        sheet.addCell(beforeDaysLabel);
        sheet.addCell(upDaysLabel);
        sheet.addCell(finalSalaryLabel);
        sheet.addCell(payTimeLabel);
        //3.循环迭代list,每一个payroll对象对应一行,每个字段对应一行的一列
        for (int i = 0; i < payrolls.size(); i++) {
            Payroll payroll = (Payroll) payrolls.get(i);
            int row = i + 1;
            //填充数据
            Label tempidLabel = new Label(0, row, payroll.getEmployee().getId().toString());
            Label tempmonthLabel = new Label(1, row, payroll.getMonth().toString());
            Label temprealNameLabel = new Label(2, row, payroll.getEmployee().getRealName());
            Label tempbaseSalaryLabel = new Label(3, row, payroll.getBaseSalary().toString());
            Label tempworkDaysLabel = new Label(4, row, payroll.getWorkDays().toString());
            Label tempafterDaysLabel = new Label(5, row, payroll.getAfterDays().toString());
            Label tempbeforeDaysLabel = new Label(6, row, payroll.getBeforeDays().toString());
            Label tempupDaysLabel = new Label(7, row, payroll.getUpDays().toString());
            if (payroll.getFinalSalary() != null) {
                Label tempfinalSalaryLabel = new Label(8, row, payroll.getFinalSalary().toString());
                sheet.addCell(tempfinalSalaryLabel);
            }
            if (payroll.getPayTime() != null) {
                Label temppayTimeLabel = new Label(9, row, payroll.getPayTime().toLocaleString());
                sheet.addCell(temppayTimeLabel);
            }
            sheet.addCell(tempidLabel);
            sheet.addCell(tempmonthLabel);
            sheet.addCell(temprealNameLabel);
            sheet.addCell(tempbaseSalaryLabel);
            sheet.addCell(tempworkDaysLabel);
            sheet.addCell(tempafterDaysLabel);
            sheet.addCell(tempbeforeDaysLabel);
            sheet.addCell(tempupDaysLabel);
        }
        //把内容中的工作簿对象的相关内容写到 输出流 里面
        workbook.write();
        //关闭工作簿
        workbook.close();
    }

    //模板下载
    @RequestMapping("download")
    @ResponseBody
    public void download(HttpServletResponse response, Long id, HttpSession session) throws Exception {
        Payroll payroll = payrollService.selectByPrimaryKey(id);
        session.setAttribute("PAYROLL_IN_SESSION", payroll);
        String fileName = new String("工资表模板".getBytes("utf-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", (new StringBuilder()).
                append("attachment;filename=").append(fileName).append(".xls").toString());
        WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
        WritableSheet sheet = workBook.createSheet("工资表模板", 0);

        sheet.addCell(new Label(0, 0, "员工编号"));
        sheet.addCell(new Label(1, 0, "月份"));
        sheet.addCell(new Label(2, 0, "员工姓名"));
        sheet.addCell(new Label(3, 0, "基本工资"));
        sheet.addCell(new Label(4, 0, "工作天数"));
        sheet.addCell(new Label(5, 0, "迟到天数"));
        sheet.addCell(new Label(6, 0, "早退天数"));
        sheet.addCell(new Label(7, 0, "补签天数"));
        sheet.addCell(new Label(8, 0, "最终工资"));
        sheet.addCell(new Label(9, 0, "结算时间"));
        workBook.write();
        workBook.close();
    }

    @PermissionName("工资单上传")
    @RequiresPermissions("payroll:importXls")
    @RequestMapping("importXls")
    @ResponseBody
    public JSONResult importXls(MultipartFile file) {
        JSONResult jsonResult = new JSONResult();
        try {
            Workbook workBook = null;
            workBook = Workbook.getWorkbook(file.getInputStream());
            Sheet sheet = workBook.getSheet(0);
            int rows = sheet.getRows();
            //设置时间的格式
            SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfPayTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 1; i < rows; i++) {
                Employee employee = new Employee();

                Payroll payroll = new Payroll();
                String contents = sheet.getCell(0, i).getContents();
                employee.setId(Long.valueOf(contents));
                payroll.setEmployee(employee);

                contents = sheet.getCell(1, i).getContents();
                payroll.setMonth(sdfMonth.parse(contents));

                contents = sheet.getCell(2,i).getContents();
                employee.setRealName(contents);
                payroll.setEmployee(employee);

                contents = sheet.getCell(3,i).getContents();
                payroll.setBaseSalary(new BigDecimal(contents));

                contents = sheet.getCell(4,i).getContents();
                payroll.setWorkDays(Integer.valueOf(contents));

                contents = sheet.getCell(5,i).getContents();
                payroll.setAfterDays(Integer.valueOf(contents));

                contents = sheet.getCell(6,i).getContents();
                payroll.setBeforeDays(Integer.valueOf(contents));

                contents = sheet.getCell(7,i).getContents();
                payroll.setUpDays(Integer.valueOf(contents));

                contents = sheet.getCell(8,i).getContents();
                payroll.setFinalSalary(new BigDecimal(contents));

                contents = sheet.getCell(9,i).getContents();
                payroll.setPayTime(sdfPayTime.parse(contents));

                payrollService.insertFromFile(payroll);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("系统崩溃了,攻城狮正在努力攻城!");
        }
        return jsonResult;
    }
}
